package com.oracle.zebrafreelytraveling.ui;

import android.app.Activity;
import android.content.Intent;
import android.net.Uri;
import android.os.Bundle;
import android.support.annotation.Nullable;
import android.support.v7.widget.DefaultItemAnimator;
import android.support.v7.widget.GridLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.text.TextUtils;
import android.util.Log;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.view.ViewGroup;
import android.widget.EditText;
import android.widget.LinearLayout;

import com.facebook.drawee.view.SimpleDraweeView;
import com.oracle.zebrafreelytraveling.R;
import com.oracle.zebrafreelytraveling.data.RequestResult.ResState;
import com.oracle.zebrafreelytraveling.data.bean.Card;
import com.oracle.zebrafreelytraveling.net.HttpManager;
import com.oracle.zebrafreelytraveling.ui.BaseRecycleAdapter.CommonAdapter;
import com.oracle.zebrafreelytraveling.ui.BaseRecycleAdapter.MultiItemTypeAdapter;
import com.oracle.zebrafreelytraveling.ui.BaseRecycleAdapter.base.ViewHolder;
import com.oracle.zebrafreelytraveling.ui.fragment.GetImgDialogFragment;
import com.oracle.zebrafreelytraveling.utils.constant.Constant;
import com.oracle.zebrafreelytraveling.utils.ConvertUtils;
import com.oracle.zebrafreelytraveling.utils.StringUtil;
import com.oracle.zebrafreelytraveling.utils.ToastUtil;
import com.oracle.zebrafreelytraveling.utils.GsonUtil;
import com.oracle.zebrafreelytraveling.utils.UserUtil;

import java.util.ArrayList;
import java.util.List;

import io.reactivex.Observer;
import io.reactivex.android.schedulers.AndroidSchedulers;
import io.reactivex.annotations.NonNull;
import io.reactivex.disposables.Disposable;
import io.reactivex.schedulers.Schedulers;

/**
 * Created by yydcnjjw on 2017/7/28.
 * 编辑帖子界面
 */

public class EtCardActivity extends BaseActitvity implements GetImgDialogFragment.OnCurrentPathListener {

    private static final String ET_TITLE = "title";
    private static final String ET_LABEL = "label";

    private MenuItem addCardMenu;
    private EditText mETTitle;
    private EditText mETContent;
    private RecyclerView mETImageRecycle;
    private CommonAdapter<String> mETImageAdapter;
    private List<String> imagePathList = new ArrayList<>();

    private Disposable mDisposable;

    private String title;
    private String label;
    @Override
    protected void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        getIntentData();
        initView();
        initRecycle();
    }

    private void getIntentData(){
        Intent intent = getIntent();
        title = intent.getStringExtra(ET_TITLE);
        label = intent.getStringExtra(ET_LABEL);
    }

    private void initView(){
        mETImageRecycle = (RecyclerView) findViewById(R.id.edit_card_image);
        mETContent = (EditText) findViewById(R.id.edit_content);
        mETTitle = (EditText) findViewById(R.id.edit_title);
        mETTitle.setText(title);

    }

    private void initRecycle(){
        imagePathList.add("res:///"+R.drawable.ic_account_circle_black_36dp);
        mETImageRecycle.setLayoutManager(new GridLayoutManager(this, 3));
        mETImageRecycle.setItemAnimator(new DefaultItemAnimator());
        mETImageAdapter = new CommonAdapter<String>(this, R.layout.item_card_img, imagePathList) {
            @Override
            protected void convert(ViewHolder holder, String s, int position) {
                SimpleDraweeView image = holder.getView(R.id.card_list_image);
                LinearLayout.LayoutParams params = new LinearLayout.LayoutParams(
                        ViewGroup.LayoutParams.MATCH_PARENT,
                        ViewGroup.LayoutParams.WRAP_CONTENT);
                params.height = ConvertUtils.dp2px(80);
                params.topMargin = ConvertUtils.dp2px(10);
                params.bottomMargin = ConvertUtils.dp2px(10);
                params.leftMargin = ConvertUtils.dp2px(5);
                params.rightMargin = ConvertUtils.dp2px(5);
                image.setLayoutParams(params);
                image.setImageURI(s);
            }
        };
        mETImageAdapter.setOnItemClickListener(new MultiItemTypeAdapter.OnItemClickListener() {
            @Override
            public void onItemClick(View view, RecyclerView.ViewHolder holder, int position) {
                if (position == imagePathList.size() - 1){
                    GetImgDialogFragment.newInstance().showDialogFragment(getFragmentManager());
                } else {
                    //TODO 放大显示
                }

            }

            @Override
            public boolean onItemLongClick(View view, RecyclerView.ViewHolder holder, int position) {
                return false;
            }
        });
        mETImageRecycle.setAdapter(mETImageAdapter);
    }

    private void addCard(){
        addCardMenu.setEnabled(false);
        String title = mETTitle.getText().toString();
        String content = mETContent.getText().toString();

        if (TextUtils.isEmpty(title) || TextUtils.isEmpty(content)){
            ToastUtil.showToast(getString(R.string.content_null));
            return;
        }
        Card card = new Card();
        card.setContent(content);
        card.setUserId(UserUtil.getUserInfoFromSP().getUserId());
        card.setImg(StringUtil.formatImageUrlList(imagePathList));
        card.setLabel(label);
        card.setTime(System.currentTimeMillis()+"");
        String cardToJson = GsonUtil.getInstance().toJson(card);
        HttpManager.getInstance().getService(Constant.BASE_URL)
                .addCards(cardToJson)
                .subscribeOn(Schedulers.io())
                .observeOn(AndroidSchedulers.mainThread())
                .subscribe(new Observer<ResState>() {
                    @Override
                    public void onSubscribe(@NonNull Disposable d) {
                        mDisposable = d;
                    }

                    @Override
                    public void onNext(@NonNull ResState resState) {
                        ToastUtil.showToast(resState.getMessage());
                    }
                    @Override
                    public void onError(@NonNull Throwable e) {
                        Log.d("addCard", e.getMessage());
                    }
                    @Override
                    public void onComplete() {

                    }
                });
    }

    @Override
    protected void onResume() {
        super.onResume();
    }

    public static void startEditCardActivity(Activity activity, String title, String label){
        Intent intent = new Intent(activity, EtCardActivity.class);
        intent.putExtra(ET_TITLE, title);
        intent.putExtra(ET_LABEL, label);
        activity.startActivity(intent);
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        addCardMenu.setEnabled(true);
        //清除 Disposable
        if (mDisposable != null && !mDisposable.isDisposed()) {
            mDisposable.dispose();
        }
    }

    @Override
    public void getPath(Uri path) {
        Log.d("addDraweeView", path+"");
        imagePathList.add(0, path+"");
        mETImageAdapter.notifyDataSetChanged();
    }

    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        getMenuInflater().inflate(R.menu.menu_et_card, menu);
        addCardMenu = menu.findItem(R.id.et_card_input);
        return true;
    }

    @Override
    public boolean onOptionsItemSelected(MenuItem item) {
        switch (item.getItemId()){
            case R.id.et_card_input:
                addCard();
                break;
        }
        return super.onOptionsItemSelected(item);
    }

    @Override
    protected int getLayoutId() {
        return R.layout.activity_edit_card;
    }
}
